using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections.Generic;

namespace Emerald4
{
    /// <summary>
    /// Manages all tablet apps. This runs automatically - no setup needed!
    /// </summary>
    public class SomniumTabletManager : MonoBehaviour
    {
        public static SomniumTabletManager Instance { get; private set; }

        // Tablet paths
        private const string HOME_BUTTON_CONTAINER = "Canvases/Tablet.XR.Tabs/Tablet.XR.HomeTab/ContentView";
        private const string REFERENCE_BUTTON = "Tablet.XR.SwitchTabBtn - My Avatar";
        private const string APPLICATIONS_PATH = "Canvases/Tablet.XR.Tabs";
        private const string BACK_BUTTON_PATH = "Canvases/Tablet.XR.StatusBar/StatusBar/LeftSideGroup/Tablet.XR.StatusBar.Back";
        private const string RESIZE_BUTTON_PATH = "Canvases/Tablet.XR.StatusBar/StatusBar/Btns/Tablet.XR.StatusBar.CapabilityBtn - Resize";

        private GameObject _tablet;
        private GameObject _originalAppsRoot;
        private Button _backButton;
        private Button _resizeButton;

        // Track all created apps
        private List<TabletApp> _activeApps = new List<TabletApp>();
        private TabletApp _currentOpenApp;

        private class TabletApp
        {
            public GameObject menuButton;
            public GameObject customAppsRoot;
            public GameObject appInstance;
            public TabletAppRegistry.TabletAppConfig config;
        }

        private void Awake()
        {
            if (Instance == null)
            {
                Instance = this;
                DontDestroyOnLoad(gameObject);
                StartCoroutine(Initialize());
            }
            else
            {
                Destroy(gameObject);
            }
        }

        private System.Collections.IEnumerator Initialize()
        {
            // Find tablet
            yield return FindTablet();

            if (_tablet == null)
            {
                Debug.LogError("[TabletManager] Failed to find tablet!");
                yield break;
            }

            // Find original apps root
            var appsTransform = _tablet.transform.Find(APPLICATIONS_PATH);
            if (appsTransform != null)
            {
                _originalAppsRoot = appsTransform.gameObject;
            }

            // Setup back button
            var backTransform = _tablet.transform.Find(BACK_BUTTON_PATH);
            if (backTransform != null)
            {
                _backButton = backTransform.GetComponent<Button>();
            }

            // Setup resize button
            var resizeTransform = _tablet.transform.Find(RESIZE_BUTTON_PATH);
            if (resizeTransform != null)
            {
                _resizeButton = resizeTransform.GetComponent<Button>();
            }

            // Notify registry we're ready
            TabletAppRegistry.NotifyManagerReady(this);

            Debug.Log("[TabletManager] ✓ Ready!");
        }

        private System.Collections.IEnumerator FindTablet()
        {
            string[] keywords = { "Tablet.XR(Clone)", "Tablet.NonXR(Clone)" };
            int attempts = 0;

            while (_tablet == null && attempts < 30)
            {
                attempts++;

                // The tablet is parented under the local player rig, not at scene root,
                // so this has to walk every transform rather than GetRootGameObjects().
                foreach (var candidate in Resources.FindObjectsOfTypeAll<Transform>())
                {
                    if (candidate.hideFlags != HideFlags.None) continue;
                    if (!candidate.gameObject.scene.IsValid()) continue;

                    foreach (var keyword in keywords)
                    {
                        if (candidate.name.Contains(keyword))
                        {
                            _tablet = candidate.gameObject;
                            Debug.Log($"[TabletManager] ✓ Found tablet: {_tablet.name}");
                            yield break;
                        }
                    }
                }

                yield return new WaitForSeconds(1f);
            }
        }

        /// <summary>
        /// Create a new app button (called by registry)
        /// </summary>
        internal void CreateAppButton(TabletAppRegistry.TabletAppConfig config)
        {
            if (_tablet == null || _originalAppsRoot == null)
            {
                Debug.LogWarning($"[TabletManager] Not ready yet, can't create button for '{config.buttonTitle}'");
                return;
            }

            var app = new TabletApp { config = config };

            // Clone the original apps root (preserves exact RectTransform/positioning)
            app.customAppsRoot = Instantiate(_originalAppsRoot, _originalAppsRoot.transform.parent);
            app.customAppsRoot.name = $"CustomApps_{config.buttonTitle}";
            app.customAppsRoot.SetActive(false);

            // Clear all children from the clone
            foreach (Transform child in app.customAppsRoot.transform)
            {
                Destroy(child.gameObject);
            }

            // Strip non-Unity scripts from the container to avoid interference
            StripNonUnityScripts(app.customAppsRoot);

            // Spawn app prefab and apply position offset if specified
            if (config.appPrefab != null)
            {
                app.appInstance = Instantiate(config.appPrefab, app.customAppsRoot.transform);
                app.appInstance.SetActive(true);

                // Apply position offset if specified
                if (config.positionOffset != Vector3.zero)
                {
                    var rectTransform = app.appInstance.GetComponent<RectTransform>();
                    if (rectTransform != null)
                    {
                        rectTransform.anchoredPosition += new Vector2(config.positionOffset.x, config.positionOffset.y);
                        rectTransform.localPosition = new Vector3(
                            rectTransform.localPosition.x,
                            rectTransform.localPosition.y,
                            rectTransform.localPosition.z + config.positionOffset.z
                        );
                        Debug.Log($"[TabletManager] Applied position offset: {config.positionOffset}");
                    }
                }
            }

            // Create menu button
            var containerTransform = _tablet.transform.Find(HOME_BUTTON_CONTAINER);
            var referenceButton = containerTransform?.Find(REFERENCE_BUTTON);

            if (referenceButton != null)
            {
                app.menuButton = Instantiate(referenceButton.gameObject, containerTransform);
                app.menuButton.name = $"CustomBtn_{config.buttonTitle}";

                // Strip custom scripts
                StripNonUnityScripts(app.menuButton);

                // Update visuals
                UpdateButtonVisuals(app.menuButton, config);

                // Hook up click
                var button = app.menuButton.GetComponent<Button>();
                if (button != null)
                {
                    button.onClick.RemoveAllListeners();
                    int appIndex = _activeApps.Count; // Capture index for closure
                    button.onClick.AddListener(() => OpenApp(appIndex));
                    button.interactable = true;
                }

                app.menuButton.SetActive(true);
            }

            _activeApps.Add(app);

            Debug.Log($"[TabletManager] ✓ Created app: {config.buttonTitle}");
        }

        /// <summary>
        /// Remove an app button by title (called by registry)
        /// </summary>
        internal void RemoveAppButton(string title)
        {
            TabletApp appToRemove = null;
            int appIndex = -1;

            for (int i = 0; i < _activeApps.Count; i++)
            {
                if (_activeApps[i].config.buttonTitle == title)
                {
                    appToRemove = _activeApps[i];
                    appIndex = i;
                    break;
                }
            }

            if (appToRemove == null)
            {
                Debug.LogWarning($"[TabletManager] Could not find app to remove: {title}");
                return;
            }

            // If this app is currently open, close it first
            if (_currentOpenApp == appToRemove)
            {
                CloseCurrentApp();
            }

            // Destroy the menu button
            if (appToRemove.menuButton != null)
            {
                Destroy(appToRemove.menuButton);
            }

            // Destroy the custom apps root (and app instance inside it)
            if (appToRemove.customAppsRoot != null)
            {
                Destroy(appToRemove.customAppsRoot);
            }

            // Remove from list
            _activeApps.RemoveAt(appIndex);

            // Re-wire button click handlers to use correct indices
            RewireButtonIndices();

            Debug.Log($"[TabletManager] ✓ Removed app: {title}");
        }

        /// <summary>
        /// Re-wire all button click handlers after an app was removed
        /// </summary>
        private void RewireButtonIndices()
        {
            for (int i = 0; i < _activeApps.Count; i++)
            {
                var app = _activeApps[i];
                if (app.menuButton != null)
                {
                    var button = app.menuButton.GetComponent<Button>();
                    if (button != null)
                    {
                        button.onClick.RemoveAllListeners();
                        int appIndex = i; // Capture for closure
                        button.onClick.AddListener(() => OpenApp(appIndex));
                    }
                }
            }
        }

        private void UpdateButtonVisuals(GameObject button, TabletAppRegistry.TabletAppConfig config)
        {
            // Update icon
            var iconTransform = button.transform.Find("Icon");
            if (iconTransform != null && config.buttonIcon != null)
            {
                var iconImage = iconTransform.GetComponent<Image>();
                if (iconImage != null)
                    iconImage.sprite = config.buttonIcon;
            }

            // Update title
            var titleTransform = button.transform.Find("Text");
            if (titleTransform != null)
            {
                var titleText = titleTransform.GetComponent<TextMeshProUGUI>();
                if (titleText != null)
                    titleText.text = config.buttonTitle;
            }
        }

        private void StripNonUnityScripts(GameObject obj)
        {
            var behaviours = obj.GetComponentsInChildren<MonoBehaviour>(true);
            foreach (var mb in behaviours)
            {
                if (mb == null) continue;

                var type = mb.GetType();
                var ns = type.Namespace ?? string.Empty;

                if (ns.StartsWith("UnityEngine") || ns.StartsWith("TMPro"))
                    continue;

                Destroy(mb);
            }
        }

        private void OpenApp(int appIndex)
        {
            if (appIndex < 0 || appIndex >= _activeApps.Count) return;

            var app = _activeApps[appIndex];

            // Close current app if any
            if (_currentOpenApp != null)
            {
                CloseCurrentApp();
            }

            // Open new app
            if (_originalAppsRoot != null)
                _originalAppsRoot.SetActive(false);

            app.customAppsRoot.SetActive(true);
            _currentOpenApp = app;

            // Add our listener to back button (don't remove others!)
            if (_backButton != null)
            {
                _backButton.gameObject.SetActive(true);
                _backButton.onClick.AddListener(CloseCurrentApp);
            }

            // Auto-resize
            if (app.config.autoResizeOnOpen && _resizeButton != null)
            {
                _resizeButton.onClick.Invoke();
            }

            Debug.Log($"[TabletManager] Opened: {app.config.buttonTitle}");
        }

        private void CloseCurrentApp()
        {
            if (_currentOpenApp == null) return;

            _currentOpenApp.customAppsRoot.SetActive(false);

            if (_originalAppsRoot != null)
                _originalAppsRoot.SetActive(true);

            // Remove only our listener (don't hide button - other apps may need it)
            if (_backButton != null)
            {
                _backButton.onClick.RemoveListener(CloseCurrentApp);
            }

            // Resize back
            if (_currentOpenApp.config.autoResizeOnOpen && _resizeButton != null)
            {
                _resizeButton.onClick.Invoke();
            }

            Debug.Log($"[TabletManager] Closed: {_currentOpenApp.config.buttonTitle}");
            _currentOpenApp = null;
        }
    }
}
